#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#define fatal(fmt, arg...) \
    do { \
        printf("[fatal] %s +%d : " fmt "\n", __FILE__, __LINE__, ## arg); \
        exit(1); \
    } while(0)


static inline void set_str(const char *file, char *str)
{
    int fd = open(file, O_WRONLY);
    if (fd < 0)
        fatal("can't open: %s", file);

    int ret = write(fd, str, strlen(str));
    if (ret < 0)
        fatal("can't write: %s", file);

    close(fd);
}

static inline int get_str(const char *file, char *str, int len)
{
    int fd = open(file, O_RDONLY);
    if (fd < 0)
        fatal("can't open: %s", file);

    int ret = read(fd, str, len);
    if (ret < 0)
        fatal("can't read: %s, len=%d", file, len);

    close(fd);

    return ret;
}

static inline void set_int(const char *file, int value)
{
    char buf[32] = {0}; // uint(-1): 4294967295

    if (snprintf(buf, sizeof(buf), "%d\n", value) < 0)
        fatal("snprintf");

    set_str(file, buf);
}

static inline int get_int(const char *file)
{
    char buf[32] = {0};

    get_str(file, buf, sizeof(buf));
    return atoi(buf);
}

